package com.pai4j.ugc.messaegqueue.consumer.redis;
import com.pai4j.common.enums.messagequeue.MessageQueueEnum;
import com.pai4j.common.service.messagequeue.consumer.AbstractRedisQueueConsumer;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.request.mess.ChatMessageRequestVO;
import com.pai4j.ugc.messaegqueue.service.AbstractPersistentMessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 消息持久化队列消费者
 *
 */
@Component
@Lazy(value = false)
@Slf4j
public class PersistentChatMessageRedisMQConsumer extends AbstractRedisQueueConsumer<ChatMessageRequestVO> {

    @Resource
    private AbstractPersistentMessageService persistentMessageService;


    public void initBean() {
        new Thread(() -> PersistentChatMessageRedisMQConsumer.this.schedule()).start();
    }

    @Override
    protected ChatMessageRequestVO convert(String s) {

        return JsonUtil.fromJson(s, ChatMessageRequestVO.class);
    }

    @Override
    protected MessageQueueEnum getMessageQueue() {

        return MessageQueueEnum.QUEUE_PERSISTENT_CHAT_MESSAGE;
    }

    @Override
    protected void receive(ChatMessageRequestVO data) {
        if (data == null) {
            return;
        }
        boolean result = persistentMessageService.persistent(data);
        // 抛出异常，重新入队
        Assert.isTrue(result, "消息持久化失败");
    }

    @Override
    protected void error(ChatMessageRequestVO data, Exception ex) {

    }
}
